package com.study.springboot2.controller;


import com.study.springboot2.entity.User;
import com.study.springboot2.service.UserService;
import com.study.springboot2.utils.*;
//import com.study.springboot2.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value="/redis")
public class RedisController extends BaseController {

//    @Autowired
//    RedisUtil redisUtil;

    @Autowired
    RedisTemplateUtil redisUtil;

    @Autowired
    UserService userService;

    /**
     * @param: []
     * @return: org.springframework.ui.ModelMap
     * @Description: 执行redis写/读/生命周期
     */
    @RequestMapping(value = "getRedis")
    @ResponseBody
    public ModelMap getRedis(){
        redisUtil.set("20182018","这是一条测试数据", RedisConstants.datebase1);
        String res = (String) redisUtil.get("20182018", RedisConstants.datebase1);

        logger.info("测试： " + res);
        //测试Redis保存对象
        User u = new User();
        u.setAge(24);
        u.setName("冯绍峰");
        redisUtil.set("20181017", SerializeUtil.serialize(u),RedisConstants.datebase1);
        byte[] user = (byte[]) redisUtil.get("20181017",RedisConstants.datebase1);
        User us = (User) SerializeUtil.unserialize(user);
        System.out.println("user="+us.toString());

        return getModelMap(StateParameter.SUCCESS, res, "执行成功");
    }

    @RequestMapping(value = "saveMysql")
    @ResponseBody
    public ModelMap save(Integer age, String name){
        //测试保存对象
        User u = new User();
        u.setAge(age);
        u.setName(name);

        userService.save(u);
        System.out.println("user="+u.toString());

        return getModelMap(StateParameter.SUCCESS, u.toString(), "执行成功");
    }

    @RequestMapping(value = "getMysql")
    @ResponseBody
    public ModelMap get(){


        List<User> userList = userService.findAll();
        System.out.println("userList="+userList.toString());

        return getModelMap(StateParameter.SUCCESS, userList, "执行成功");
    }

    @RequestMapping(value="/view")
    public String view(HttpServletRequest request){

        List<User> list = userService.findAll();
        request.setAttribute("list", list);
        logger.info("返回列表页面");

        return "/firstPage";
    }
}
